<template>
	<view class="fixedbody" style="padding: 0;">
		<view style="min-height: 63vh;">
		<!-- 报名费 -->
		<view class="rrcard" v-if="bill.cptRegistrationFee">
				<uni-collapse>
					<uni-collapse-item titleBorder="none" :border="false"  :open="true">
						<template v-slot:title>
							<view>
								<view class="h1">{{bill.cptRegistrationFee?.name}}</view>
								<view class="h2"> 
								<text v-if="bill.cptRegistrationFee?.count">{{bill.cptRegistrationFee?.count}}人</text>   
								合计：<text class="orange">{{bill.cptRegistrationFee?.totalFee}}元</text></view>
							</view>
						</template>
						<view class="content">
							<!-- 人员列表 -->
							<uni-list v-if="bill.cptRegistrationFee?.info" :border="false">
								<uni-list-item  v-for="(m,index) in bill.cptRegistrationFee?.info" :key="index">
								<template v-slot:header>
									<view class="slot-box" v-show="m.personInfo.picUrl">
										<image class="slot-image" :src="m.personInfo.picUrl" mode="aspectFill"></image>
									</view>
								</template>
								<template v-slot:body>
									<view class="slotbody">
										<view class="name">{{m.personInfo.realName}}</view>
										<text v-if="m.personInfo.sex=='0'">女</text>
										<text v-else>男</text>
									</view>
								</template>
								<template v-slot:footer>
									<view class="slotfooter">
										￥{{m.registrationFee}}
									</view>
								</template>
								</uni-list-item>
							</uni-list>
						</view>
					</uni-collapse-item>
				</uni-collapse>
		</view>
		<!-- 兼项 -->
		<view class="rrcard" v-if="bill.cptCompatibleFee?.totalFee!='0'">
			<uni-collapse>
				<uni-collapse-item titleBorder="none" :border="false"  :open="true">
					<template v-slot:title>
						<view>
							<view class="h1">{{bill.cptCompatibleFee?.name}}</view>
							<view class="h2"> 
							<text v-if="bill.cptCompatibleFee?.count">{{bill.cptCompatibleFee?.count}}人</text>   
							合计：<text class="orange">{{bill.cptCompatibleFee?.totalFee}}元</text></view>
						</view>
					</template>
					<view class="content">
						<!-- 人员列表 -->
						<uni-list v-if="bill.cptCompatibleFee?.info" :border="false">
							<uni-list-item  v-for="(m,index) in bill.cptCompatibleFee?.info" :key="index">
							<template v-slot:header>
								<view class="slot-box" v-show="m.personInfo.picUrl">
									<image class="slot-image" :src="m.personInfo.picUrl" mode="aspectFill"></image>
								</view>
							</template>
							<template v-slot:body>
								<view class="slotbody">
									<view class="name">{{m.personInfo.realName}}</view>
									<text v-if="m.personInfo.sex=='0'">女</text>
									<text v-else>男</text>
								</view>
							</template>
							<template v-slot:footer>
								<view class="slotfooter">
									￥{{m.compatibleFee}}
								</view>
							</template>
							</uni-list-item>
						</uni-list>
					</view>
				</uni-collapse-item>
			</uni-collapse>
		</view>
		<!-- 保险 -->
		<view class="rrcard" v-if="bill.cptInsuranceFee">
				<uni-collapse>
					<uni-collapse-item titleBorder="none" :border="false" :open="true">
						<template v-slot:title>
							<view>
								<view class="h1">{{bill.cptInsuranceFee.name}}</view>
								<view class="h2"> 
								<text v-if="bill.cptInsuranceFee.count">{{bill.cptInsuranceFee.count}}人</text>   
								合计：<text class="orange">{{cptInsuranceFee}}元</text></view>
							</view>
						</template>
						<view class="content">
							<!-- 人员列表 -->
							<uni-list v-if="bill.cptInsuranceFee?.info" :border="false">
								<checkbox-group @change="radioChange">
									<uni-list-item v-for="(m,index) in bill.cptInsuranceFee.info" :key="index" >
									
									<template v-slot:header>
										<view class="slot-box" v-show="m.personInfo.picUrl">
											<image class="slot-image" :src="m.personInfo.picUrl" mode="aspectFill"></image>
										</view>
									</template>
									<template v-slot:body>
										<view class="slotbody">
											<view class="name">{{m.personInfo.realName}}</view>
											<text v-if="m.personInfo.idcType == 0">身份证：</text>
											<text v-else-if="m.personInfo.idcType == 1">护照：</text>
											<text v-else>其他：</text>
											<text>{{m.personInfo.idcCode}}</text>
										</view>
		
									</template>
									<template v-slot:footer>
										<view class="slotfooter" v-if="bill.cptInsuranceFee.must=='0'">
											<text v-if="m.lastBuyFlag=='1'">已购</text>
											<view v-else>
												<checkbox :value="m.personId"/>
												￥{{m.insuranceFee}}
											</view>
										</view>
										<view class="slotfooter" v-else>￥{{m.insuranceFee}}</view>
									</template>
									</uni-list-item>
								</checkbox-group>
							</uni-list>
						</view>
					</uni-collapse-item>
				</uni-collapse>
		</view>
		<!-- 其他 -->
		<view class="rrcard" v-if="bill.otherFee?.totalFee!='0'">
				<uni-collapse>
					<uni-collapse-item titleBorder="none" :border="false" :open="true">
						<template v-slot:title>
							<view>
								<view class="h1">{{bill.otherFee?.name}}</view>
								<view class="h2"> 
								<text v-if="bill.otherFee?.count">{{bill.otherFee?.count}}人</text>   
								合计：<text class="orange">{{othermm}}元</text></view>
							</view>
						</template>
						<view class="content">
							<!-- 人员列表 -->
							<uni-list v-if="bill.otherFee?.info" :border="false">
								<checkbox-group @change="otherFeeChange">
								<uni-list-item v-for="(m,index) in bill.otherFee.info" :key="index"  
								:title="m.personInfo.realName" :note="m.personalCptProjectName" 
								:thumb="m.personInfo.picUrl" thumb-size="lg">
									<template v-slot:footer>
										<view class="slotfooter">
											<checkbox v-if="bill.otherFee.allBringOwn=='1'" checked :value="m.personId"/>
											￥{{m.otherFee}}
										</view>
									</template>
								</uni-list-item>
								</checkbox-group>
							</uni-list>
						</view>
					</uni-collapse-item>
				</uni-collapse>
		</view>

		</view>
		<view class="fBottom">
			<view class="pp" v-if="bill.cptRegistrationFee?.totalFee>0">{{bill.cptRegistrationFee?.name}}:<text>{{bill.cptRegistrationFee?.totalFee}}元</text></view>
			<view class="pp" v-if="bill.cptCompatibleFee?.totalFee>0">{{bill.cptCompatibleFee?.name}}:<text>{{bill.cptCompatibleFee?.totalFee}}元</text></view>
			<view class="pp" v-if="cptInsuranceFee>0">{{bill.cptInsuranceFee?.name}}:<text>{{cptInsuranceFee}}元</text></view>
			<view class="pp" v-if="othermm>0">{{bill.otherFee?.name}}:<text>{{othermm}}元</text></view>
			<view class="pp" v-if="bill.cptDepositFee?.totalFee>0">{{bill.cptDepositFee?.name}}:<text>{{bill.cptDepositFee?.totalFee}}元</text></view>
			<view class="pp" v-if="bill.teamFee?.totalFee>0">{{bill.teamFee?.name}}:<text>{{bill.teamFee?.totalFee}}元</text></view>
			<view class="txr">
				合计：<text class="orange">{{finialFee}}元</text>
			</view>
			<button class="payBtn mt-30" @click="submitBill">
				提交订单
			</button>
		</view>
		

		<uni-popup ref="payMationPop" :is-mask-click="false">
			<view class="payMationPopBody">
				<view class="t">线下支付</view>
				<view @click="copyOrg" class="hoverBg">
					<view class="p">公司：<text>{{organizerInfo.organizerName}}</text></view>
					<view class="p">开户：<text>{{organizerInfo.organizerBank}}</text></view>
					<view class="p">账号：<text>{{organizerInfo.organizerAccount}}</text></view>
					<view class="p">应付：<text class="orange">{{organizerInfo.organizerFee}}元</text></view>
				</view>

				<view @click="copyPlat" class="hoverBg" v-if="bill.cptInsuranceFee?.usePlatform=='1'" style="margin: 40rpx 0 0;">
					<view class="p">公司：<text>{{platformInfo.platformName}}</text></view>
					<view class="p">开户：<text>{{platformInfo.platformBank}}</text></view>
					<view class="p">账号：<text>{{platformInfo.platformAccount}}</text></view>
					<view class="p">应付：<text class="orange">{{platformInfo.platformFee}}元</text></view>
				</view>
				<view style="display: flex;">
					<button class="btn btn1" @click="tipForPayMation">查看报项</button>
					<!-- <button class="btn btn1" @click="goSignDetail"> </button> -->
					<button class="btn btn1" @click="download">下载凭证</button>
				</view>
			</view>
		</uni-popup>
		
		<uni-popup ref="popPayType" type="bottom" :is-mask-click="false" safe-area background-color="#fff">
			<view class="PopcloseBtn" @click="alertGiveup">
				<uni-icons type="closeempty" size="30" color="#999"></uni-icons>
			</view>

			<view class="rrcard" style="padding-bottom: 100rpx;">
				<view class="moneyNum">￥<text>{{finialFee}}</text></view>
				<view class="t">支付方式</view>
				<view class="whitebg">
					<radio-group @change="payChange">
						<!-- 支付方式 0 会员卡支付 1 微信支付 2 线下支付 -->
						<label class="uni-list-cell uni-list-cell-pd">
							<view class="littleimgBox">
								<image class="littleimg" src="@/static/zf01.png"></image>微信支付
							</view>
							<view>
								<radio checked="checked" value="1" />
							</view>
						</label>
						<label class="uni-list-cell uni-list-cell-pd">
							<view class="littleimgBox">
								<image class="littleimg" src="@/static/zf02.png"></image>会员卡支付(余额：￥{{myBalance}})
							</view>
							<view>
								<radio checked="checked" value="0" />
							</view>
						</label>
						<label class="uni-list-cell uni-list-cell-pd">
							<view class="littleimgBox">
								<image class="littleimg" src="@/static/zf03.png"></image>线下支付
							</view>
							<view>
								<radio checked="checked" value="2" />
							</view>
						</label>
					</radio-group>
				</view>
			
				<button class="payBtn" @click="goPay">确认交易</button>
			</view>
		</uni-popup>
		<uni-popup ref="giveup" type="dialog">
			<uni-popup-dialog type="success" confirmText="放弃" cancelText="继续支付" content="是否放弃本次支付" @confirm="cancelPay"  @close="closeGiveup">
			</uni-popup-dialog>
		</uni-popup>
		<uni-popup ref="alertPayWrong" type="dialog">
			<uni-popup-dialog type="error" confirmText="查看订单详情" content="支付失败" @confirm="goDetail" @close="goDetail">
			</uni-popup-dialog>
		</uni-popup>
		<uni-popup ref="alertPayOk" type="dialog">
			<uni-popup-dialog type="success" confirmText="查看订单详情" cancelText="下载凭证" content="支付成功" @confirm="goSignDetail"  @close="download">
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script setup>
import { reactive, toRefs } from 'vue';
import * as match from '@/common/match.js';
import * as api from '@/common/api.js';
import { onLoad } from '@dcloudio/uni-app';
const data = reactive({
	memberList:[1,2,3],
	myBalance:'',
	form:{},
	payMationPop:null,
	alertDialog:null,
	alertPayOk:null,
	alertPayWrong:null,
	bill:{},
	finialFee:'',
	cptInsuranceFee:'',
	othermm:'',
	popPayType:null,
	giveup:null,
	payType:'2',
	organizerInfo:{},
	platformInfo:{}
})
const {memberList,myBalance,form,payMationPop,alertDialog,alertPayOk,alertPayWrong,
bill,finialFee,cptInsuranceFee,othermm,popPayType,payType,giveup,organizerInfo,platformInfo} = toRefs(data);
const app = getApp();
let cptId
let entryId
let personId
let groupId
let buyInsurancePersonIds = ''
let hasOthersPersonIds = ''
let orderId = ''
const currUser = uni.getStorageSync('currUser');
onLoad(option=>{
	console.log(option)
	// 获取余额
	if(option.groupId){
		entryId = option.groupId
		groupId = option.groupId
	}
	if(option.personId){
		entryId = option.personId
		personId = option.personId
	}
	cptId = option.cptId
	getTotalFee()
	api.getMyBalance().then((res) => {
		myBalance.value = res.data
	})
})
let bxdanjia
let otherdanjia
let baseTotal
function getTotalFee(){
	match.getTotalFee({
		entryId:entryId,
		cptId:cptId
	}).then(res=>{
		bill.value = res.data
		cptInsuranceFee.value = bill.value.cptInsuranceFee.totalFee
		othermm.value = bill.value.otherFee.totalFee
		bxdanjia = bill.value.cptInsuranceFee?.info[0].insuranceFee || 0
		finialFee.value = bill.value.totalFee
		baseTotal=parseFloat(bill.value.totalFee)-parseFloat(bill.value.otherFee?.totalFee||0)
		console.log(baseTotal,finialFee.value)
		var arr = []
		if(bill.value.otherFee.info.length>0){
			otherdanjia = bill.value.otherFee.info[0].otherFee
			for(const ren of bill.value.otherFee.info){
				arr.push(ren.personId)
			}
			hasOthersPersonIds = arr.toString()
			console.log(hasOthersPersonIds)
		}
	})
}
function payChange(evt) {
	payType.value = evt.detail.value
}
function getTotal(){
	finialFee.value=parseFloat(baseTotal)+parseFloat(cptInsuranceFee.value)+parseFloat(othermm.value)
}
// 保险费
function radioChange(e){
	console.log(e.detail.value.length)
	let arr = e.detail.value
	buyInsurancePersonIds = arr.toString()
	console.log(bxdanjia)
	cptInsuranceFee.value = arr.length*bxdanjia
	getTotal()
	// finialFee.value = parseFloat(cptInsuranceFee.value) + parseFloat(bill.value.totalFee)
}
// 其他
function otherFeeChange(e) {
	console.log(e.detail.value)
	let arr = e.detail.value
	hasOthersPersonIds = arr.toString()
	
	othermm.value = arr.length*otherdanjia
	getTotal()
	// finialFee.value = parseFloat(finialFee.value) - parseFloat(bill.value.otherFee.totalFee) + parseFloat(othermm.value)
	
}

function submitBill(){
		// 保存购买信息
		var obj = {
			insruanceFee:cptInsuranceFee.value,
			buyInsurancePersonIds:buyInsurancePersonIds||'',
			otherFee:othermm.value,
			bringPersonIds:hasOthersPersonIds||'',
			cptId:cptId,
			groupId:groupId
		}
		creatBill(obj)
	
}
// 生成订单
function creatBill(obj){
	match.commitSign(obj).then(res=>{
		console.log(res.data)
		orderId = res.data
		// 弹出支付方式窗口
		popPayType.value.open()
	})
}
function tipForPayMation(){
	uni.showModal({
		title: '提示',
		content: '点击信息复制到剪贴板',
		cancelText:'好的',
		confirmText:'我已复制',
		success: function (res) {
			if (res.confirm) {
				// 去订单详情页
				goSignDetail()
			} else if (res.cancel) {
				console.log('返回');
			}
		}
	});
}
function copyOrg(){
	let str = `公司：111；开户行：；账户：；`
	uni.setClipboardData({
		data: str,
		success: function () {
			console.log('success');
		}
	});
}
function copyPlat(){
	let str = `公司：222；开户行：；账户：；`
	uni.setClipboardData({
		data: str,
		success: function () {
			console.log('success');
		}
	});
}
function goPay(){
	const nowOpenId = uni.getStorageSync('nowOpenId')
	if(payType.value==''){
		uni.showToast({
			title: '请选择支付方式',
			icon:'none',
			duration: 2000
		});
		return
	}
	if(payType.value=='1'){
		uni.showLoading({
			title: '支付中...'
		});
		let obj = {
			orderId:orderId,
			platformType: 0,
			payType:1,
			openId:nowOpenId
		}
		match.payMatch(obj).then(res=>{
			if (res.data.weixinData) {
				wePay(res.data.weixinData,orderId)
			} else {
				alertPayOk.value.open()
			}
		}).catch(() => {
			alertPayWrong.value.open()
		}).finally(() => {
			uni.hideLoading()
		})
	}else{
		match.payMatch({orderId:orderId,payType:payType.value}).then(res=>{
			if(res.data.success=='1'){
				console.log('支付成功')
				if(payType.value=='2'){
					// 线下支付
					organizerInfo.value = res.data.org
					platformInfo.value = res.data.plat
					popPayType.value.close()
					payMationPop.value.open()
				} else {
					uni.redirectTo({
						url: `/pages_match/match/matchPayDone?cptId=${cptId}&groupId=${groupId}&chargeFlag='1'&orderId=${orderId}&amount=${res.data.amount}&payType=${res.data.payType}`
					})
				}
		
			}else{
				console.log('支付失败')
				alertPayWrong.value.open()
			}
		})
	}

}
	function wePay(configdata,orderId) {
		// console.log(configdata)
		// 微信支付
		uni.requestPayment({
			"provider": "wxpay",
			"appId": configdata.appId,
			"nonceStr": configdata.nonceStr,
			"package": configdata.packageValue, // 随机字符串
			"timeStamp": configdata.timeStamp, // 时间戳（单位：秒）
			"signType": configdata.signType, // 签名，这里用的 MD5/RSA 签名
			"paySign": configdata.paySign,
			success(res) {
				alertPayOk.value.open()
				match.maPayConfirm({
					orderId:orderId,
					successFlag:true
				}).then((res)=>{
					
				})
			},
			fail(e) {
				uni.showToast({
					title: '支付取消',
					icon: 'none',
					duration: 2000
				})
				match.maPayConfirm({
					orderId:orderId,
					successFlag:false
				}).then((res)=>{
					
				})

			}
		})
	}


function alertGiveup(){
	giveup.value.open()
}
function closeGiveup(){
	giveup.value.close()
}
function cancelPay(){
	// 点击放弃
	goDetail()
}

function goDetail() {
	// 前往订单详情
	uni.redirectTo({
		url: `/pages/usercenter/matchBillDetail?id=${orderId}`
	})
}
function goSignDetail() {
	// 前往订单详情
	uni.redirectTo({
		url: `/pages/usercenter/matchSignDetail?id=${cptId}&groupId=${groupId}&auditStatus=1`
	})
}
function dialogClose() {
	alertDialog.value.close()
}
function dialogConfirm() {
	uni.showLoading({
		title: '支付中...'
	});
}
function download(){
	match.downloadpz(cptId,groupId).then(res=>{
		goWebView(res.data)
	})
}
function goWebView(url) {
	console.log(url)
	url = url.replace("http://", "https://")
	uni.showLoading({
		title: '下载中'
	});
	uni.downloadFile({
		url: url,
		success: function(res) {
				uni.hideLoading();
				var filePath = res.tempFilePath;
				uni.showLoading({
					title: '正在打开'
				});
				uni.openDocument({
					filePath: filePath,
					showMenu: true,
					success: function(res) {
						uni.hideLoading();
					},
					fail: function(err) {
						uni.hideLoading();
						uni.showToast({
							title: err,
							icon: 'none',
							duration: 2000
						});
					}
				});
			},
		fail: function(error) {
			uni.hideLoading();
			uni.showToast({
				title: `下载失败`,
				icon: 'none',
				duration: 2000
			});
		}
	});
}


</script>

<style lang="scss" scoped>
	.whitebg{background: #fff;margin-top: 15rpx;  border-radius: 20rpx; margin-bottom: 180rpx;}
	.rrcard {margin-top: 30rpx;
		.box {padding: 0 0 1px;margin: 20rpx 0 0;}
	}
	.littleimgBox {
		display: flex;
		align-items: center;
	}
	
	.littleimg {
		width: 50rpx;
		height: 50rpx;
		margin-right: 15rpx;
	}
	
	:deep(.uni-collapse){border-radius: 30rpx;}
	:deep(.uni-collapse-item){margin: 0 0 10rpx;}
	.uni-list-cell::after{display: none;}
	.payMationPopBody{background: #FFFFFF;    width: 550rpx; border-radius: 15px; padding: 50rpx;box-sizing: border-box;
		.t{text-align: center;color: #7B7F83;font-size: 34rpx;margin:0 0 50rpx;}
		.p{color: #7B7F83;font-size: 30rpx;
			text{color: #1A1A1A;}
		}
		.btn{margin-top:60rpx;}
	}
.payBtnBox {
	width: 750rpx;background:#fff;
	line-height: 90rpx;
	position: fixed;
	bottom: 0;
	display: flex;justify-content: space-between;
	height: 120rpx;
}

.totalPrice{color: #7B7F83;font-size: 24rpx;padding: 0 0 0 20rpx;
	.orange{font-size: 45rpx;}
}
.h1{font-size: 30rpx;margin: 0 0 20rpx;}
.h2{color: #7B7F83;font-size: 28rpx;
	text{margin-right: 20rpx;}
}
:deep(.uni-list-item__container){padding-left: 0;}
.slot-box image{    height: 40px;  width: 40px;    border-radius: 50%;    margin: 0 10px 0 0;}
.slotbody{    width: 100%;
	.name{font-size: 14px;
    color: #3b4144;
    overflow: hidden;}
	text{font-size:24rpx;}
}
.slotfooter{    display: flex;
    align-items: center;
    color: #FF8124;}

</style>
